import { toRefs } from 'vue'
import { useMapStore } from '@/stores/map' // 使用pinia

export default function useCatalog() {
  var drawLayer
  const { map } = toRefs(useMapStore())
  /*---------------- 将摄像头图层高亮显示 ---------------*/
  function monitorHighlight() {
    if (!drawLayer) {
      Query.queryByAttr({
        where: ``,
        // where: `name='${input.value}'`,
        service: { name: 'guanggu', layerId: '4' },
        callback: querySuccess,
      })
    }
    preparePopup()
  }

  function monitorRemove() {
    // map.value.removeLayer(drawLayer)
    if (drawLayer) {
      map.value.getLayers().pop()
      drawLayer = null
      content.innerHTML = ''
      closer.removeEventListener('click', closePopup)
    }
  }

  //查询成功回调
  function querySuccess(result) {
    console.log(result)

    //初始化Zondy.Format.PolygonJSON类
    var format = new Zondy.Format.PolygonJSON()
    //将MapGIS要素JSON反序列化为ol.Feature类型数组
    var features = format.read(result)

    //实例化一个矢量图层drawLayerr用于高亮显示结果
    var drawSource = new ol.source.Vector({
      wrapX: false,
    })
    drawSource.addFeatures(features)
    drawLayer = new ol.layer.Vector({
      source: drawSource,
      style: new ol.style.Style({
        image: new ol.style.Icon({
          //设置图标点
          anchor: [0.6, 32],
          //图标起点
          anchorOrigin: 'top-right',
          //指定x值为图标点的x值
          anchorXUnits: 'fraction',
          //指定Y值为像素的值
          anchorYUnits: 'pixels',
          //偏移
          offsetOrigin: 'top-right',
          // offset:[0,10],
          //图标缩放比例
          // scale:0.5,
          //透明度
          opacity: 0.75,
          //图标的url
          src: '/src/assets/images/摄像头设置图标-07.png',
        }),
      }),
    })
    console.log(drawLayer)
    console.log(map.value.getLayers().getArray())
    map.value.addLayer(drawLayer)
    console.log(map.value.getLayers().getArray())
  }

  /*------------------ 动态popup ----------------*/
  var container
  var content
  var closer
  const popup = new ol.Overlay({
    //要转换成overlay的HTML元素
    element: container,
    // element: updateContainer("emmm1", "./images/道路.mp4"),
    //当前窗口可见
    autoPan: true,
    //Popup放置的位置
    positioning: 'bottom-center',
    //是否应该停止事件传播到地图窗口
    stopEvent: true,
    autoPanAnimation: {
      //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
      duration: 250,
    },
  })

  function preparePopup() {
    container = document.getElementById('popup-monitor')
    closer = document.createElement('a')
    closer.href = '#'
    closer.id = 'popup-closer'
    closer.className = 'ol-popup-closer'
    // elementDiv.innerText = info.att.text;
    closer.addEventListener('click', closePopup)
    content = document.createElement('div')
    content.id = 'popup-content'
    container.appendChild(closer)
    container.appendChild(content)
    map.value.addOverlay(popup) // 为map添加点击事件监听，渲染弹出popup
    map.value.on('click', function (e) {
      // 获取当前点击的点是否存在要素, 并返回
      const feature = map.value.forEachFeatureAtPixel(
        //
        e.pixel,
        function (feature, layer) {
          return feature
        }
      )
      if (feature) {
        console.log(feature)
        if (popup.getPosition() != undefined) {
          closePopup()
        }
        var position = feature.getGeometry().flatCoordinates
        popup.setElement(
          updateContainer(
            feature.values_.values_['位置'],
            feature.values_.values_.URL
          )
        ) // '标题'， './images/道路.mp4'
        popup.setPosition(position)
      }
    })
    //为map添加鼠标移动事件监听，当指向标注时改变鼠标光标状态
    map.value.on('pointermove', function (e) {
      var pixel = map.value.getEventPixel(e.originalEvent)
      var hit = map.value.hasFeatureAtPixel(pixel)
      map.value.getTargetElement().style.cursor = hit ? 'pointer' : ''
    })
  }

  function updateContainer(title = 'emmm', src = './images/道路.mp4') {
    // 二. 将dom转换成overlay
    // var content = document.getElementById('popup-content')
    content.id = 'popup-content'
    // //新增div元素
    var elementDiv = document.createElement('div')
    elementDiv.className = 'marker-text'
    // elementDiv.innerText = info.att.text;
    elementDiv.innerText = title
    // 为content添加div子节点
    content.appendChild(elementDiv)
    //新增video元素
    var elementVideo = document.createElement('video')
    elementVideo.className = 'marker-video'
    // elementVideo.src = info.att.imgURL;
    elementVideo.src = src
    elementVideo.autoplay = 'true'
    elementVideo.loop = 'true'
    elementVideo.muted = 'true'
    // 为content添加img子节点
    content.appendChild(elementVideo)
    return container
  }

  //添加关闭按钮的单击事件（隐藏popup）
  function closePopup() {
    content.innerHTML = ''
    //未定义popup位置
    popup.setPosition(undefined)
    //失去焦点
    closer.blur()
    return false
  }
  return {
    monitorHighlight,
    monitorRemove,
  }
}
